package com.speedchina.permission.base.i18n;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * 国际化服务类
 *
 * @author hank
 * @create 2021-04-07 上午10:09
 **/
@Component
public class I18nService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private MessageSource messageSource;

    /**
     * 初始化
     *
     * @return
     */
    private MessageSource initMessageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(3600);
        return messageSource;
    }

    public String getMessage(String code) {
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes != null ? requestAttributes.getRequest() : null;
        return getMessage(request, code);
    }

    public String getMessage(HttpServletRequest request, String code) {
        if (messageSource == null) {
            synchronized (this) {
                if (messageSource == null) {
                    messageSource = initMessageSource();
                }
            }
        }
        String language = request == null ? null : request.getHeader("language");
        Locale locale = null;
        if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(language)) {
            locale = Locale.CHINA;
        } else if (Locale.ENGLISH.getLanguage().equals(language)) {
            locale = Locale.ENGLISH;
        } else { //其余的不正确的默认就是本地的语言
            locale = request.getLocale();
        }

        String result = null;
        try {
            result = messageSource.getMessage(code, null, locale);
        } catch (NoSuchMessageException e) {
            logger.error("Cannot find the error message of internationalization, return the original error message.");
        }

        return result == null ? code : result;
    }
}
